<template>
  <div class="drawer-header display-flex flex-align flex-justify-between">
    <div>
      <p class="title">{{ $t('preferences.preferences') }}</p>
      <p class="sub-title">
        {{ $t('preferences.customPreferencesLivePreview') }}
      </p>
    </div>
    <div class="display-flex flex-align">
      <icon-container v-if="!isReset" class="disabled">
        <core-reset-icon class="reset-icon"></core-reset-icon>
      </icon-container>
      <icon-container v-else @click="handleReset">
        <el-tooltip
          popper-class="tooltip-light"
          effect="light"
          :content="$t('preferences.dataChangedClickToReset')"
          :show-arrow="false"
          :offset="10"
        >
          <el-badge is-dot color="rgb(var(--core-primary-color))">
            <core-reset-icon class="reset-icon disabled"></core-reset-icon>
          </el-badge>
        </el-tooltip>
      </icon-container>
      <icon-container style="margin-left: 2px" @click="handlerClose">
        <core-cross-mark-icon></core-cross-mark-icon>
      </icon-container>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import IconContainer from '../icon-container/index.vue'
import { usePreferencesStore } from '@/stores'
import {
  basePreferences,
  PREFERENCES_KEY
} from '@/stores/modules/preferences/utils'
import { isEqual } from '@/utils'

const emits = defineEmits(['close'])

const preferencesStore = usePreferencesStore()

const handleReset = () => {
  isReset.value = false
  preferencesStore.resetPreferences()
}

const handlerClose = () => {
  emits('close')
}

const isReset = ref(false)

watch(
  () => preferencesStore.$state,
  (newVal) => {
    if (!isEqual(newVal, basePreferences)) {
      isReset.value = true
    }
    localStorage.setItem(PREFERENCES_KEY, JSON.stringify(newVal))
  },
  { deep: true, immediate: true }
)

defineOptions({
  name: 'CorePreferencesDrawerHeader'
})
</script>

<style scoped lang="scss">
.drawer-header {
  padding: 12px 16px;
  border-bottom: 1px solid var(--core-border-color-01);

  .title {
    color: var(--core-text-color-03);
  }

  .sub-title {
    margin-top: 8px;
    font-size: 12px;
    color: var(--core-text-color-06);
  }

  .reset-icon {
    color: var(--core-text-color-03);
  }

  .disabled {
    pointer-events: none;
    opacity: 0.5;
  }
}
</style>
